<template>
  <section class="member-center">
    <h1 class="title">会员中心</h1>
    
    <div v-if="user" class="main-content">
      <!-- 会员状态卡片 -->
      <div class="status-card" :class="{ 'member-active': user.isMember }">
        <div class="status-header">
          <h2 class="status-title">
            {{ user.isMember ? '会员状态' : '立即开通会员' }}
            <span v-if="user.isMember" class="member-badge" :style="{ backgroundColor: memberInfo.color }">
              {{ memberInfo.name }}
            </span>
          </h2>
          <div v-if="user.isMember" class="expiry-info">
            有效期至：{{ formatDate(user.memberExpires) }}
          </div>
        </div>
        
        <div class="status-body">
          <div v-if="user.isMember" class="member-details">
            <div class="member-info">
              <p class="welcome">欢迎回来，{{ user.username }}！</p>
              <p class="level-desc">您当前是<span :style="{ color: memberInfo.color }">{{ memberInfo.name }}</span></p>
            </div>
            
            <div class="member-features">
              <h3>会员特权</h3>
              <ul>
                <li v-for="(feature, index) in memberInfo.features" :key="index">
                  <span class="check">✓</span> {{ feature }}
                </li>
              </ul>
            </div>
          </div>
          
          <div v-else class="non-member-prompt">
            <p class="prompt-text">开通会员，享受更多专属特权！</p>
          </div>
        </div>
      </div>
      
      <!-- 会员套餐选择 -->
      <div class="plans-section">
        <h2 class="section-title">会员套餐</h2>
        <div class="plans-grid">
          <div 
            v-for="(plan, level) in memberLevels" 
            :key="level"
            class="plan-card"
            :class="{ 
              'selected': selectedLevel === level,
              'current': user.isMember && user.memberLevel === level 
            }"
            @click="selectPlan(level)"
          >
            <div class="plan-header">
              <h3 class="plan-name">{{ plan.name }}</h3>
              <div class="plan-price">
                <span class="price">¥{{ plan.price }}</span>
                <span class="period">/月</span>
              </div>
            </div>
            
            <div class="plan-features">
              <ul>
                <li v-for="(feature, index) in plan.features" :key="index">
                  <span class="check">✓</span> {{ feature }}
                </li>
              </ul>
            </div>
            
            <div class="plan-footer">
              <span v-if="user.isMember && user.memberLevel === level" class="current-badge">当前套餐</span>
              <button 
                v-else 
                class="select-btn" 
                :style="{ backgroundColor: plan.color }"
                @click.stop="selectPlan(level)"
              >
                选择
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 购买选项 -->
      <div class="purchase-section">
        <h2 class="section-title">选择时长</h2>
        <div class="duration-options">
          <button 
            v-for="option in durationOptions" 
            :key="option.months"
            class="duration-btn"
            :class="{ selected: selectedMonths === option.months }"
            @click="selectDuration(option.months)"
          >
            {{ option.label }}
            <span v-if="option.discount" class="discount">{{ option.discount }}</span>
          </button>
        </div>
        
        <div class="summary">
          <div class="summary-row">
            <span>套餐：</span>
            <span>{{ memberLevels[selectedLevel].name }}</span>
          </div>
          <div class="summary-row">
            <span>时长：</span>
            <span>{{ selectedMonths }}个月</span>
          </div>
          <div class="summary-row total">
            <span>总计：</span>
            <span class="total-price">¥{{ calculateTotal() }}</span>
          </div>
        </div>
        
        <button 
          class="purchase-btn"
          @click="purchaseMembership"
          :disabled="processing"
        >
          {{ processing ? '处理中...' : (user.isMember ? '立即续费' : '立即开通') }}
        </button>
      </div>
      
      <!-- 会员记录 -->
      <div v-if="user.isMember" class="history-section">
        <h2 class="section-title">会员记录</h2>
        <div class="history-info">
          <div class="history-item">
            <span class="label">开通时间：</span>
            <span>{{ user.createdAt ? formatDate(user.createdAt) : '未知' }}</span>
          </div>
          <div class="history-item">
            <span class="label">上次更新：</span>
            <span>{{ user.lastMemberUpdate ? formatDate(user.lastMemberUpdate) : '未知' }}</span>
          </div>
        </div>
        
        <button 
          class="cancel-btn"
          @click="confirmCancel"
          :disabled="processing"
        >
          {{ processing ? '处理中...' : '取消会员' }}
        </button>
      </div>
    </div>
    
    <div v-else class="not-logged-in">
      <p>请先登录</p>
      <button class="login" @click="goLogin">去登录</button>
    </div>
    
    <!-- 确认对话框 -->
    <div v-if="showConfirm" class="confirm-dialog">
      <div class="confirm-content">
        <h3>{{ confirmTitle }}</h3>
        <p>{{ confirmMessage }}</p>
        <div class="confirm-buttons">
          <button class="cancel" @click="cancelConfirm">取消</button>
          <button class="confirm" @click="doConfirm">确认</button>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentUser, activateMember, cancelMember, loadUsers } from '@/utils/auth'

const router = useRouter()
const user = ref(null)
const selectedLevel = ref('standard')
const selectedMonths = ref(1)
const processing = ref(false)
const showConfirm = ref(false)
const confirmTitle = ref('')
const confirmMessage = ref('')
const confirmAction = ref(null)

// 会员等级定义
const memberLevels = {
  standard: { name: '标准会员', color: '#00a1d6', price: 19, features: ['无广告观看', '高清画质', '基础下载'] },
  premium: { name: '高级会员', color: '#8b5cf6', price: 39, features: ['无广告观看', '超高清画质', '高速下载', '专属内容'] }
}

// 时长选项
const durationOptions = [
  { months: 1, label: '1个月', discount: '' },
  { months: 3, label: '3个月', discount: '9折' },
  { months: 6, label: '6个月', discount: '8折' },
  { months: 12, label: '12个月', discount: '7折' }
]

// 计算当前会员信息
const memberInfo = computed(() => {
  if (!user.value?.isMember) return { name: '普通用户', features: [], color: '#9ca3af' }
  return memberLevels[user.value.memberLevel] || memberLevels.standard
})

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 选择套餐
function selectPlan(level) {
  selectedLevel.value = level
}

// 选择时长
function selectDuration(months) {
  selectedMonths.value = months
}

// 计算总价
const calculateTotal = computed(() => {
  const basePrice = memberLevels[selectedLevel.value].price
  let discount = 1
  
  // 根据时长计算折扣
  if (selectedMonths.value === 3) discount = 0.9
  else if (selectedMonths.value === 6) discount = 0.8
  else if (selectedMonths.value === 12) discount = 0.7
  
  return Math.round(basePrice * selectedMonths.value * discount)
})

// 购买或续费会员
function purchaseMembership() {
  if (!user.value) return
  
  showConfirm.value = true
  confirmTitle.value = user.value.isMember ? '确认续费' : '确认开通'
  confirmMessage.value = `确定要${user.value.isMember ? '续费' : '开通'}${memberLevels[selectedLevel.value].name}，时长${selectedMonths.value}个月，总计¥${calculateTotal.value}吗？`
  confirmAction.value = async () => {
    try {
      processing.value = true
      await activateMember(user.value.username, selectedMonths.value, selectedLevel.value)
      // 刷新用户信息
      user.value = getCurrentUser()
      showMessage('操作成功！')
    } catch (error) {
      showMessage(error.message || '操作失败，请重试', true)
    } finally {
      processing.value = false
      showConfirm.value = false
    }
  }
}

// 确认取消会员
function confirmCancel() {
  showConfirm.value = true
  confirmTitle.value = '取消会员'
  confirmMessage.value = '确定要取消会员吗？取消后将无法享受会员特权，直到下次开通。'
  confirmAction.value = async () => {
    try {
      processing.value = true
      await cancelMember(user.value.username)
      // 刷新用户信息
      user.value = getCurrentUser()
      showMessage('会员已取消')
    } catch (error) {
      showMessage(error.message || '操作失败，请重试', true)
    } finally {
      processing.value = false
      showConfirm.value = false
    }
  }
}

// 取消确认
function cancelConfirm() {
  showConfirm.value = false
  confirmAction.value = null
}

// 确认操作
function doConfirm() {
  if (typeof confirmAction.value === 'function') {
    confirmAction.value()
  }
}

// 显示消息（这里简化处理，实际项目中可以使用更完善的消息提示组件）
function showMessage(text, isError = false) {
  alert(text)
}

// 去登录
function goLogin() {
  router.push('/login')
}

// 加载用户信息
onMounted(() => {
  user.value = getCurrentUser()
  
  // 监听用户登录状态变化
  window.addEventListener('auth-changed', () => {
    user.value = getCurrentUser()
  })
  
  // 如果用户已登录，设置默认选中的套餐为用户当前的会员等级
  if (user.value?.isMember) {
    selectedLevel.value = user.value.memberLevel
  }
})
</script>

<style scoped>
.member-center {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.title {
  margin: 0 0 24px 0;
  font-size: 28px;
  font-weight: 800;
  text-align: center;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 状态卡片 */
.status-card {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  padding: 24px;
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
}

.status-card.member-active {
  border-color: #00a1d6;
  box-shadow: 0 0 20px rgba(0, 161, 214, 0.1);
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

.status-title {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 12px;
}

.member-badge {
  padding: 4px 12px;
  border-radius: 16px;
  color: white;
  font-size: 14px;
  font-weight: 600;
}

.expiry-info {
  color: #6b7280;
  font-size: 14px;
}

.member-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  align-items: center;
}

.member-info .welcome {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.member-info .level-desc {
  margin: 0;
  color: #6b7280;
}

.member-features h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
}

.member-features ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.member-features li {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #4b5563;
}

.member-features .check {
  color: #10b981;
  font-weight: bold;
}

.non-member-prompt {
  text-align: center;
  padding: 20px 0;
}

.prompt-text {
  font-size: 18px;
  color: #6b7280;
  margin: 0;
}

/* 套餐部分 */
.plans-section {
  margin-top: 8px;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 20px;
  font-weight: 700;
}

.plans-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.plan-card {
  background: var(--surface);
  border: 2px solid var(--border);
  border-radius: var(--radius);
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.plan-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow);
}

.plan-card.selected {
  border-color: #00a1d6;
  box-shadow: 0 0 20px rgba(0, 161, 214, 0.15);
}

.plan-card.current {
  border-color: #10b981;
  position: relative;
}

.plan-card.current::before {
  content: '当前套餐';
  position: absolute;
  top: -10px;
  right: 20px;
  background: #10b981;
  color: white;
  padding: 2px 10px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 600;
}

.plan-header {
  margin-bottom: 16px;
}

.plan-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 700;
}

.plan-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.price {
  font-size: 24px;
  font-weight: 800;
  color: #374151;
}

.period {
  color: #6b7280;
}

.plan-features ul {
  list-style: none;
  padding: 0;
  margin: 0 0 16px 0;
}

.plan-features li {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #4b5563;
  font-size: 14px;
}

.plan-features .check {
  color: #10b981;
  font-weight: bold;
}

.plan-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.current-badge {
  background: #d1fae5;
  color: #065f46;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 14px;
  font-weight: 600;
}

.select-btn {
  background: #00a1d6;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 999px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.2s ease;
}

.select-btn:hover {
  opacity: 0.9;
  transform: scale(1.05);
}

/* 购买部分 */
.purchase-section {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  padding: 24px;
  box-shadow: var(--shadow-sm);
}

.duration-options {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.duration-btn {
  padding: 10px 20px;
  border: 2px solid var(--border);
  border-radius: 999px;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  font-weight: 500;
}

.duration-btn:hover {
  border-color: #00a1d6;
}

.duration-btn.selected {
  border-color: #00a1d6;
  background: #e0f2fe;
  color: #0369a1;
}

.discount {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #f43f5e;
  color: white;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: 600;
}

.summary {
  background: #f9fafb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #4b5563;
}

.summary-row.total {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #e5e7eb;
  font-weight: 700;
}

.total-price {
  font-size: 20px;
  color: #374151;
}

.purchase-btn {
  width: 100%;
  padding: 14px;
  border: none;
  border-radius: 999px;
  background: #00a1d6;
  color: white;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.2s ease;
}

.purchase-btn:hover:not(:disabled) {
  background: #0284c7;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 161, 214, 0.3);
}

.purchase-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 历史部分 */
.history-section {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  padding: 24px;
  box-shadow: var(--shadow-sm);
}

.history-info {
  background: #f9fafb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.history-item {
  display: flex;
  margin-bottom: 8px;
  color: #4b5563;
}

.history-item:last-child {
  margin-bottom: 0;
}

.history-item .label {
  font-weight: 600;
  margin-right: 8px;
  min-width: 80px;
}

.cancel-btn {
  width: 100%;
  padding: 12px;
  border: 2px solid #f43f5e;
  border-radius: 999px;
  background: white;
  color: #f43f5e;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.2s ease;
}

.cancel-btn:hover:not(:disabled) {
  background: #f43f5e;
  color: white;
}

.cancel-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 未登录状态 */
.not-logged-in {
  text-align: center;
  padding: 60px 20px;
  background: var(--surface);
  border-radius: var(--radius);
}

.not-logged-in p {
  font-size: 18px;
  color: #6b7280;
  margin-bottom: 20px;
}

.not-logged-in .login {
  padding: 12px 32px;
  border: none;
  border-radius: 999px;
  background: #00a1d6;
  color: white;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.2s ease;
}

.not-logged-in .login:hover {
  background: #0284c7;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 161, 214, 0.3);
}

/* 确认对话框 */
.confirm-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.confirm-content {
  background: white;
  border-radius: 12px;
  padding: 24px;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.confirm-content h3 {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 700;
}

.confirm-content p {
  margin: 0 0 20px 0;
  color: #4b5563;
}

.confirm-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.confirm-buttons .cancel {
  padding: 8px 16px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: white;
  color: #4b5563;
  cursor: pointer;
  transition: all 0.2s ease;
}

.confirm-buttons .cancel:hover {
  background: #f9fafb;
}

.confirm-buttons .confirm {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background: #00a1d6;
  color: white;
  cursor: pointer;
  transition: all 0.2s ease;
}

.confirm-buttons .confirm:hover {
  background: #0284c7;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .member-details {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .plans-grid {
    grid-template-columns: 1fr;
  }
  
  .status-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .duration-options {
    flex-direction: column;
  }
  
  .duration-btn {
    width: 100%;
    text-align: center;
  }
}
</style>